package com.gitee.zeric.tenantdb.demo.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.gitee.zeric.tenantdb.config.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * MyBatisPlus配置
 *
 * @author zj
 * @date 2022/11/25
 */
@Slf4j
@EnableTransactionManagement
@Configuration
public class MybatisSqlSessionFactoryBeanAutoConfiguration {

    @Bean
    public MybatisSqlSessionFactoryBean sqlSessionFactoryBean(DynamicDataSource dynamicDataSource, MybatisPlusProperties mybatisPlusProperties) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        if (ArrayUtil.isNotEmpty(mybatisPlusProperties.getMapperLocations())) {
            sessionFactory.setMapperLocations(resolveMapperLocations(mybatisPlusProperties.getMapperLocations()));
        }
        if (StrUtil.isNotBlank(mybatisPlusProperties.getTypeAliasesPackage())) {
            sessionFactory.setTypeAliasesPackage(mybatisPlusProperties.getTypeAliasesPackage());
        }
        if (StrUtil.isNotBlank(mybatisPlusProperties.getTypeHandlersPackage())) {
            sessionFactory.setTypeHandlersPackage(mybatisPlusProperties.getTypeHandlersPackage());
        }

//        if (mybatisPlusProperties.getGlobalConfig() != null) {
//            sessionFactory.setGlobalConfig(mybatisPlusProperties.getGlobalConfig());
//        }
        GlobalConfig globalConfig=new GlobalConfig();
//        globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());
        sessionFactory.setGlobalConfig(globalConfig);

        //配置数据源，此处配置为关键配置，如果没有将 dynamicDataSource作为数据源则不能实现切换
        sessionFactory.setDataSource(dynamicDataSource);
        return sessionFactory;
    }

    @Bean
    public PlatformTransactionManager transactionManager(DynamicDataSource dynamicDataSource) {
        // 配置事务管理, 使用事务时在方法头部添加@Transactional注解即可
        return new DataSourceTransactionManager(dynamicDataSource);
    }

    public Resource[] resolveMapperLocations(String[] mapperLocations) {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<Resource> resources = new ArrayList<>();
        if (ArrayUtil.isNotEmpty(mapperLocations)) {
            for (String mapperLocation : mapperLocations) {
                try {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                } catch (IOException e) {
                    log.error("Get myBatis resources happened exception", e);
                }
            }
        }

        return resources.toArray(new Resource[resources.size()]);
    }

}
